//
//  ModelingPublishVC.m
//  ShrimpCrowdordering
//
//  Created by jimmy on 2018/8/28.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ModelingPublishVC.h"
#import "OrigPubInputTextCell.h"
#import "OrigPubSelectBtnCell.h"
#import "OrigPubPhotoTextViewCell.h"
#import "OrigPubTitleHeaderView.h"
#import <QBImagePickerController.h>
#import <AFNetworking.h>
#import "TabBarViewController.h"
#import "ModelingSelectPublishCell.h"
#import "UIView+Utils.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import "OrigPubAddConceptPhotoTextCell.h"
#import "CommitOrderViewController.h"
#import "MoreDetailViewController.h"
#import "CenterAlertView.h"
#import "GKCover.h"
#import "CropPicsViewController.h"

@interface ModelingPublishVC ()<UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,QBImagePickerControllerDelegate,UITextViewDelegate>

@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) UITextView  * textView;

@property (nonatomic, strong) NSArray  * headerTitleAry; // 区头 标题
@property (nonatomic, strong) NSArray  * titleArray; // 第 3区前面的 标题
@property (nonatomic, strong) NSArray  * numInputTitleAry; // 第 4区 数字输入框

///播放器对象
@property (nonatomic,strong)  AVPlayer        * player;
@property (nonatomic,strong)  AVPlayerItem    * currentPlayerItem;
@property (nonatomic,strong)  AVPlayerLayer   * avLayer;
///视频地址
@property (nonatomic,strong)  NSURL           * videoUrl;
///是否是上传视频
@property (nonatomic,assign)  BOOL             isVedioUpload;
///上传的视频连接
@property (nonatomic,strong)  NSString         * videoUrlStr;
///上传的视频的封面
@property (nonatomic,strong)  NSString         * videoUrlPageStr;
///存放第0区图片的数组 或者 上传单个视频 存放图片或视频的 数组
@property (nonatomic, strong) NSMutableArray * imageAry;

///存放第二区图片的数组
@property (nonatomic,strong)  NSMutableArray  * twoImageArr;
///
@property (nonatomic, strong) UIImage        * selectImage;
///选择多张图片时候的pickerController
//@property (nonatomic, strong) UIImagePickerController * pickerMoreVC;
///选择单张张图片时候的pickerController
@property (nonatomic, strong) UIImagePickerController * pickerOneVC;
/// 因为两个选图片的 区域 不同，所以要分开区别
@property (nonatomic, assign) BOOL  isSelectTwoSection;

// 标题参数
@property (nonatomic, copy)   NSString       * param_title;
///设计理念
@property (nonatomic,copy)    NSString       * designIdea;
///新增设计理念
@property (nonatomic,copy)    NSString       * neDesignIdea;
///存放新增理念和图片的数组
@property (nonatomic, strong) NSMutableArray * proIdeasArray;
///新增图片的参数
@property (nonatomic, strong) UIImage        * param_image;
///存放每一对新增设计理念和新增图片的字典
@property (nonatomic,strong)  NSDictionary  * proIdeasDict;
// 主要是用来 过度 第一 是点击下一个图片是判断上一个的 输入框有没有输入， 第二 只有一对的时候 在提交的时候要判断 输入框是否输入
@property (nonatomic, strong) UIImage  * tempImage;
@property (nonatomic, copy)   NSString * tempInpuText;
/// 判断是选择图片还是 替换图片
@property (nonatomic, assign) BOOL  isSelectImage;
/// 替换图片的行数
@property (nonatomic, assign) NSInteger  changeImageRow;

///打赏金额的字符串
@property (nonatomic,copy)    NSString       * rewardMoney;

///多张图片时选中的序数，默认是第0 个
@property (nonatomic,assign)  NSInteger        selectPicsIndex ;
///一共有几个区
@property (nonatomic,assign)  NSInteger        sectionNum;

///第0区图片的url参数
@property (nonatomic, strong) NSMutableArray<NSString *>   * zero_imageUrl;
///第2区图片的url参数
@property (nonatomic, strong) NSMutableArray<NSString *>   * two_imageUrl;

///最大打赏金额
@property (nonatomic,copy)    NSString * rewardMount;

@end

@implementation ModelingPublishVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setTitle:@"建模发布"];
    self.selectPicsIndex = 0;
    self.isSelectImage = YES;
    self.isVedioUpload = NO;
    self.isSelectTwoSection = YES;
    [self updateData];
    [self updateViewUI];
    [self getRewarMount];

}

#pragma mark - 初始化 数据
- (void)updateData
{
    self.imageAry = [NSMutableArray array];
    self.proIdeasArray = [NSMutableArray array];
    self.proIdeasDict = [NSDictionary dictionary];
    self.headerTitleAry = @[@"标题:", @"设计理念:", @"新增图片:"];
    self.titleArray = @[@"选择性别",@"年       龄",@"季       节",@"款       型",@"尺       码",@"配       饰",@"频       道"];//,@"场       景"
    self.numInputTitleAry = @[@"打赏金额"];
    self.zero_imageUrl = [NSMutableArray array];
    self.two_imageUrl = [NSMutableArray array];
    self.twoImageArr = [NSMutableArray array];
}

#pragma mark - 初始化 UI 视图
- (void)updateViewUI
{
    [self setTableViewUI];
}

- (void)setTableViewUI
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(40)) style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    self.pickerOneVC = [[UIImagePickerController alloc] init];
    self.pickerOneVC.delegate = self;
    self.pickerOneVC.view.tag = 1000;
    
//    self.pickerMoreVC = [[UIImagePickerController alloc] init];
//    self.pickerMoreVC.delegate = self;
//    self.pickerMoreVC.view.tag = 1001;
    
    UIButton *publishBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - ScreenX375(49) - NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, ScreenX375(49))];
    [publishBtn setTitle:@"发布" forState:UIControlStateNormal];
    [publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    publishBtn.backgroundColor = REXADECIMALCOLOR(@"#fd4d4d");
    publishBtn.titleLabel.font = Kfont(16);
    [publishBtn addTarget:self action:@selector(publish) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:publishBtn];
}

#pragma mark - 提交
-(void)publish
{
    [self uploadPics];
}

#pragma mark - 上传图片
-(void)uploadPics
{
    if (self.param_title.length == 0) {
        [HttpManager showNoteMsg:@"请填写标题"];
        return;
    }
    if (self.designIdea.length == 0) {
        [HttpManager showNoteMsg:@"请填写设计理念"];
        return;
    }
    if (self.imageAry.count == 0) {
        [HttpManager showNoteMsg:@"请选择封面图片"];
        return;
    }
    if (self.proIdeasArray.count == 0) {
        [HttpManager showNoteMsg:@"请填写设计理念"];
        return;
    }
    if (self.rewardMoney.length == 0) {
        [HttpManager showNoteMsg:@"请填写打赏金额"];
        return;
    }
    if ([self.rewardMoney integerValue] > 3) {
        [HttpManager showNoteMsg:@"打赏金额应小于等于3"];
        return;
    }
    __weak __typeof(self) weakSelf = self;
    if (self.isVedioUpload == YES) {
        self.videoUrl = [NSURL URLWithString:[self.videoUrl.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""]];
        [HttpManager uploadVideoNSURL:self.videoUrl success:^(id successResponse) {
            NSString *url = successResponse[0];
            NSString *url1 = [url stringByReplacingOccurrencesOfString:@"(" withString:@""];
            NSString *url2 = [url1 stringByReplacingOccurrencesOfString:@")" withString:@""];
            weakSelf.videoUrlStr = url2;
            [HttpManager uploadImageArr:self.twoImageArr success:^(id successResponse) {
                weakSelf.two_imageUrl = successResponse;
                [HttpManager uploadImageArr:self.imageAry success:^(id successResponse) {
                    NSString *urlPage = successResponse[0];
                    NSString *urlPage1 = [urlPage stringByReplacingOccurrencesOfString:@"(" withString:@""];
                    NSString *urlPage2 = [urlPage1 stringByReplacingOccurrencesOfString:@")" withString:@""];
                    weakSelf.videoUrlPageStr = urlPage2;
                    
                    [weakSelf uploadData];
                }];
                
            }];
        }];
    }else {
        [HttpManager uploadImageArr:weakSelf.imageAry success:^(id successResponse) {
            weakSelf.zero_imageUrl = successResponse;
            [HttpManager uploadImageArr:self.twoImageArr success:^(id successResponse) {
                weakSelf.two_imageUrl = successResponse;
                [weakSelf uploadData];
            }];
        }];
    }
}

- (void)uploadData
{
    NSMutableArray *proIdeas_Array = [NSMutableArray array];
    for (int i = 0; i < self.proIdeasArray.count; i++) {
        AddConceptModel * model = self.proIdeasArray[i];
        NSString * picUrl = self.two_imageUrl[i];
        
        NSMutableDictionary * proIdesa_dic = [NSMutableDictionary dictionary];
        //[proIdesa_dic setValue:@"" forKey:@"id"];
        //[proIdesa_dic setValue:@"" forKey:@"proId"];
        [proIdesa_dic setValue:model.idea forKey:@"idea"];
        [proIdesa_dic setValue:picUrl forKey:@"pic"];
        [proIdeas_Array addObject:proIdesa_dic];
    }
    NSLog(@"%@",self.proIdeasArray);
    NSLog(@"%@",proIdeas_Array);
    
    NSString *urlStr = [NSString stringWithFormat:@"%@api/publish",REQUESTHEADER];
    NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"userId":kNSUDefaultReadKey(@"userId"),
                                                                                     @"proName":self.param_title,//产品名 标题
                                                                                     @"designIdea":self.designIdea,//设计理念
                                                                                     @"proIdeas":proIdeas_Array,//新增设计理念数组(存放的是一对：新增的设计理念和新增的图片)
                                                                                     @"sex":self.sexStr,//选择的性别
                                                                                     @"ages":self.ageStr,//选择的年龄
                                                                                     @"season":self.seasonStr,//选择的季节
                                                                                     @"type":self.typeStr,//选择的款型
                                                                                     @"size":self.sizeStr,//选择的尺码
                                                                                     @"ornament":self.accessoryStr,//选择的配饰
                                                                                     @"channelName":self.channelStr,//选择的频道
                                                                                     @"rewardAmount":self.rewardMoney,//打赏金额
                                                                                     @"status":@"1",
                                                                                     @"garmentPic":self.modelImageUrl,//成衣图 number类型？
                                                                                     @"channelId":[NSString stringWithFormat:@"%ld",(long)self.channelId],
                                                                                     @"picIds":self.picIdsArray//图片ID
                                                                                     ,@"isPublish":@"1"
                                                                                     }];
    if (self.isVedioUpload == YES) {
        NSArray *coverPicsArray = @[self.videoUrlPageStr];
        
        [parameter setValue:coverPicsArray forKey:@"coverPics"];
        [parameter setValue:self.videoUrlStr forKey:@"videoUrl"];
    }else{
        [parameter setValue:self.zero_imageUrl forKey:@"coverPics"];
    }
    __weak __typeof(self) weakSelf = self;
    [HttpManager postHttpRequestByPost:urlStr andParameter:parameter success:^(id successResponse) {
        if ([successResponse[@"code"] integerValue] == 200) {
            [HttpManager hideWait];
            [HttpManager showNoteMsg:@"发布成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                MoreDetailViewController *vc = [[MoreDetailViewController alloc] init];
                vc.proId = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"product"][@"id"]];
                vc.isPublish = YES;
                [weakSelf.navigationController pushViewController:vc animated:true];
            });
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showNoteMsg:@"上传失败"];
    }];
}

#pragma mark - 获取作品最大打赏金额
-(void)getRewarMount
{
    NSLog(@"%@",kNSUDefaultReadKey(@"userId"));
    __weak __typeof(self) weakSelf = self;
    NSString *rewardUrl = [NSString stringWithFormat:@"%@api/getRewardAmount",REQUESTHEADER];
    
    [HttpManager postHttpRequestByGet:rewardUrl andParameter:nil success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            
            weakSelf.rewardMount = [successResponse[@"data"] valueForKey:@"amount"];
            
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

#pragma mark - 选择是上传视频还是图片
-(void)selectIsVedioUpload
{
    //显示提示框
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"请选择上传视频或是上传图片"  message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* picsAction = [UIAlertAction actionWithTitle:@"上传图片" style:UIAlertActionStyleDefault   handler:^(UIAlertAction * action) {
        //响应事件
        self.isVedioUpload = NO;
        [self addOnePhoto];
        NSLog(@"action = %@", action);
    }];
    UIAlertAction* vedioAction = [UIAlertAction actionWithTitle:@"上传视频" style:UIAlertActionStyleDefault   handler:^(UIAlertAction * action) {
        //响应事件
        self.isVedioUpload = YES;
        [self actionVideo];
        NSLog(@"action = %@", action);
    }];
    [alert addAction:picsAction];
    [alert addAction:vedioAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 添加一张图片
- (void)addOnePhoto
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *send = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerOneVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.pickerOneVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        self.pickerOneVC.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:self.pickerOneVC animated:YES completion:nil];
    }];
    UIAlertAction *get = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerOneVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.pickerOneVC.mediaTypes = @[(NSString *)kUTTypeImage];
        self.pickerOneVC.allowsEditing = NO;
        [self presentViewController:self.pickerOneVC animated:YES completion:nil];
    }];
    
    [alert addAction:cancel];
    [alert addAction:send];
    [alert addAction:get];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 上传单个视频
- (void)actionVideo
{
    UIAlertController *alertController = \
    [UIAlertController alertControllerWithTitle:@""
                                        message:@"上传视频"
                                 preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = \
    [UIAlertAction actionWithTitle:@"从视频库选择"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * _Nonnull action) {
                               NSLog(@"从视频库选择");
                               self.pickerOneVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                               self.pickerOneVC.mediaTypes = @[(NSString *)kUTTypeMovie];
                               self.pickerOneVC.allowsEditing = NO;
                               
                               [self presentViewController:self.pickerOneVC animated:YES completion:nil];
                           }];
    UIAlertAction *cameraAction = \
    [UIAlertAction actionWithTitle:@"录像"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * _Nonnull action) {
                               NSLog(@"录像");
                               self.pickerOneVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                               self.pickerOneVC.cameraDevice = UIImagePickerControllerCameraDeviceRear;
                               self.pickerOneVC.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
                               self.pickerOneVC.videoQuality = UIImagePickerControllerQualityType640x480;
                               self.pickerOneVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
                               self.pickerOneVC.allowsEditing = YES;
                               
                               [self presentViewController:self.pickerOneVC animated:YES completion:nil];
                           }];
    UIAlertAction *cancelAction = \
    [UIAlertAction actionWithTitle:@"取消"
                             style:UIAlertActionStyleCancel
                           handler:^(UIAlertAction * _Nonnull action) {
                               NSLog(@"取消");
                           }];
    [alertController addAction:photoAction];
    [alertController addAction:cameraAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL   *vedioUrl = [info objectForKey:UIImagePickerControllerMediaURL];
    __weak __typeof(self) weakSelf = self;
    //获取用户选择或拍摄的是照片还是视频
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        if (self.isSelectTwoSection == YES) {
            if (self.isSelectImage == YES) {
                [self.twoImageArr addObject:image];
                self.tempImage = image;
            }else{
                if (self.changeImageRow >= self.proIdeasArray.count) {
                    return;
                }
                self.tempImage = image;
                [self.twoImageArr removeObjectAtIndex:self.changeImageRow];
                [self.twoImageArr insertObject:image atIndex:self.changeImageRow];
                AddConceptModel * model = self.proIdeasArray[self.changeImageRow];
                model.picImage = image;
            }
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            
        }else{
            CropPicsViewController *cropVC = [[CropPicsViewController alloc] init];
            cropVC.fixImage = image;
            cropVC.transportFixPicsBlock = ^(UIImage *fixImage) {
                [weakSelf.imageAry insertObject:fixImage atIndex:0];
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
                [weakSelf.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [self.navigationController pushViewController:cropVC animated:true];
        }
    }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            //如果是拍摄的视频, 则把视频保存在系统多媒体库中
            NSLog(@"video path: %@", info[UIImagePickerControllerMediaURL]);
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            // 获取视频总时长
            CGFloat lengthTime = [self getVideoLength:info[UIImagePickerControllerMediaURL]];
            NSLog(@"%f",lengthTime);
            //压缩视频
            self.videoUrl = [self condenseVideoNewUrl:vedioUrl];
            [self getVideoPreViewImage:vedioUrl];
            //视频上传
            if (lengthTime >30.0f) {
                [HttpManager showNoteMsg:@"视频文件过大，请重新选择后再上传"];
                return;
            }
            [library writeVideoAtPathToSavedPhotosAlbum:info[UIImagePickerControllerMediaURL] completionBlock:^(NSURL *assetURL, NSError *error) {
                if (!error) {
                    NSLog(@"视频保存成功");
                } else {
                    [HttpManager showNoteMsg:@"视频文件过大，请重新选择后再上传"];
                    NSLog(@"视频保存失败");
                }
            }];
        }
        else{
            // 获取视频总时长
            CGFloat lengthTime = [self getVideoLength:vedioUrl];
            NSLog(@"%f",lengthTime);
            //压缩视频
            self.videoUrl = [self condenseVideoNewUrl:vedioUrl];
            //视频上传
            if (lengthTime >30.0f) {
                [HttpManager showNoteMsg:@"视频文件过大，请重新选择后再上传"];
                return;
            }
            [self getVideoPreViewImage:vedioUrl];
        }
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (NSURL *)condenseVideoNewUrl: (NSURL *)url
{
    // 沙盒目录
    NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *destFilePath = [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"video.mp4"]];
    NSURL *destUrl = [NSURL fileURLWithPath:destFilePath];
    //将视频文件copy到沙盒目录中
    NSFileManager *manager = [NSFileManager defaultManager];
    NSError *error = nil;
    [manager copyItemAtURL:url toURL:destUrl error:&error];
    NSLog(@"压缩前--%.2fk",[self getFileSize:destFilePath]);
    // 进行压缩
    AVAsset *asset = [AVAsset assetWithURL:destUrl];
    /**
     NSString *const AVAssetExportPresetLowQuality; // 低质量
     NSString *const AVAssetExportPresetMediumQuality;
     NSString *const AVAssetExportPresetHighestQuality; //高质量
     */
    //创建视频资源导出会话
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    // 创建导出的url
    NSString *resultPath = [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"video.mp4"]];
    session.outputURL = [NSURL fileURLWithPath:resultPath];
    // 必须配置输出属性
    session.outputFileType = @"com.apple.quicktime-movie";
    // 导出视频
    [session exportAsynchronouslyWithCompletionHandler:^{
        NSLog(@"压缩后---%.2fk",[self getFileSize:resultPath]);
        NSLog(@"视频导出完成");
    }];
    return session.outputURL;
}
// 获取视频的大小
- (CGFloat) getFileSize:(NSString *)path
{
    NSFileManager *fileManager = [[NSFileManager alloc] init] ;
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }
    return filesize;
}

// 获取视频时间
- (CGFloat) getVideoLength:(NSURL *)URL
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}

#pragma mark - 获取视频第一帧
- (UIImage*) getVideoPreViewImage:(NSURL *)path
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    
    [self.imageAry insertObject:videoImage atIndex:0];
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    
    return videoImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.pickerOneVC dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDelegate/UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section  == 1){
        return 1;
    }else if (section  == 2){
        return self.proIdeasArray.count+1;//数组里有几个数据，实际要比这个多一，因为要可以继续新增
    }else if (section  == 3) {
        return 7;
    }else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section == 0) {
        return SCREEN_WIDTH - ScreenX375(60) + ScreenX375(160) + self.imageAry.count / 3 * ScreenX375(110);
    }else if (section  == 1){
        return ScreenX375(142);
    }else if (section  == 2){
        return ScreenX375(400);
    }else if (section  == 3) {
        return ScreenX375(60);
    }else{
        return ScreenX375(60);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return  ScreenX375(60);
    }else if (section == 3 || section == 2){
        return 0.01;
    }
    else{
        return ScreenX375(10);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString * placeholder = nil;
    NSString * subTitle = nil;
    if (section == 0) {
        placeholder = @"请输入标题";
    }
    if (section == 0) {
        OrigPubTitleHeaderView * headerView = [[OrigPubTitleHeaderView alloc] initWithTitle:self.headerTitleAry[0] placeholder:placeholder subTitle:subTitle height:ScreenX375(60)];
        [headerView setInputText:self.param_title];
        __weak __typeof(self) weakSelf = self;
        headerView.inputChangeBlock = ^(NSString *string) {
            weakSelf.param_title = string;
        };
        return headerView;
    }
    if (section == 1) {
        OrigPubTitleHeaderView * headerView = [[OrigPubTitleHeaderView alloc] initWithTitle:self.headerTitleAry[1] placeholder:placeholder subTitle:subTitle height:ScreenX375(60)];
        [headerView setInputText:self.param_title];
        return headerView;
    }
    if (section == 2 || section == 3 || section == 4) {
        UIView * view = [UIView new];
        view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
        return view;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [UIView new];
    view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    __weak __typeof(self) weakSelf = self;
//    if (section == 0) {
//        self.isSelectTwoSection = NO;
//    }
//    if (section == 2) {
//        self.isSelectTwoSection = YES;
//    }
    if (section == 0) {//上传封面
        static NSString *cellId = @"MoreImgCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            self.isSelectTwoSection = NO;
        }
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        
        UIImageView *imageV = [[UIImageView alloc] init];
        imageV.frame = CGRectMake(ScreenX375(30), ScreenX375(10), SCREEN_WIDTH - ScreenX375(60), SCREEN_WIDTH - ScreenX375(60));
        imageV.backgroundColor = UIColorFromRGB(@"#f2f2f2", 1);
        imageV.tag = 100;
        imageV.layer.masksToBounds = YES;
        imageV.layer.cornerRadius = 6.0;
        imageV.contentMode = UIViewContentModeScaleAspectFill;
        [cell addSubview:imageV];
        UILabel *label = [[UILabel alloc] init];
        label.tag = 101;
        label.centerX = imageV.centerX-ScreenX375(80);
        label.centerY = imageV.centerY-ScreenX375(10);
        label.size = CGSizeMake(ScreenX375(100), ScreenX375(20));
        label.text = @"上传封面";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = Kfont(15);
        label.textColor = UIColorFromRGB(@"#888888", 1);
        if (self.imageAry.count > 0) {
            imageV.image = self.imageAry[self.selectPicsIndex];
            label.hidden = YES;
        }
        [imageV addSubview:label];
        
        if (self.isVedioUpload) {
            self.avLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
            self.avLayer.videoGravity = AVLayerVideoGravityResize;
            
            self.avLayer.frame = CGRectMake(ScreenX375(30), ScreenX375(10), SCREEN_WIDTH - ScreenX375(60), SCREEN_WIDTH - ScreenX375(60));
            [cell.layer addSublayer:self.avLayer];
        }
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(30), imageV.bottom+ScreenX375(10), ScreenX375(300), ScreenX375(16))];
        titleLabel.text = @"注：可以上传多张照片或单一视频";
        titleLabel.textColor = UIColorFromRGB(@"#f21934", 1);
        titleLabel.font = Kfont(13);
        [cell addSubview:titleLabel];
        
        for (int i = 0; i < self.imageAry.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(30) + i % 3 * ScreenX375(110), imageV.bottom + ScreenX375(45) + i / 3 * ScreenX375(120), ScreenX375(100), ScreenX375(100))];
            imageView.image = self.imageAry[i];
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, ScreenX375(20), ScreenX375(100), ScreenX375(80))];
            [button addTarget:self action:@selector(seeDetailBigPic:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 10000 + i;
            [imageView addSubview:button];
            imageView.userInteractionEnabled = YES;
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            [cell addSubview:imageView];
            
            UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(30) + i % 3 * ScreenX375(110) + ScreenX375(80), imageV.bottom + ScreenX375(45) + i / 3 * ScreenX375(120), ScreenX375(20), ScreenX375(20))];
            [deleteBtn setImage:ImageWithName(@"删除标签") forState:UIControlStateNormal];
            deleteBtn.tag = 20000 + i;
            [deleteBtn addTarget:self action:@selector(deleteImg:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:deleteBtn];
        }
        
        if ((!self.isVedioUpload && self.imageAry.count < 9) || (self.isVedioUpload && self.imageAry.count < 1)) {
            UIButton *addPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            addPhotoBtn.frame = CGRectMake(ScreenX375(30) + self.imageAry.count % 3 * ScreenX375(110), imageV.bottom + ScreenX375(45) + self.imageAry.count / 3 * ScreenX375(120), ScreenX375(100), ScreenX375(100));
            addPhotoBtn.backgroundColor = UIColorFromRGB(@"#f2f2f2", 1);
            addPhotoBtn.layer.masksToBounds = YES;
            addPhotoBtn.layer.cornerRadius = 6.0;
            [addPhotoBtn setImage:[UIImage imageNamed:@"+"] forState:UIControlStateNormal];
            [addPhotoBtn addTarget:self action:@selector(selectIsVedioUpload) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:addPhotoBtn];
        }
        return cell;
    }
    else if (section  == 1){//设计理念
        OrigPubPhotoTextViewCell * cell = [OrigPubPhotoTextViewCell cellWithTableView:tableView andIndexPath:indexPath andCellHeight:ScreenX375(142) placeholder:@"请输入您的设计理念" note:nil centerTitleIsHidden:YES btnImage:NO];
        __weak __typeof(self) weakSelf = self;
        [cell setInputText:self.designIdea];
        [cell hiddenButton:YES];
        cell.inputChangeBlock = ^(NSString *string) {
            weakSelf.designIdea = string;
        };
        return cell;
    }else if (section  == 2 ) {//新增图片和设计理念的区
        OrigPubAddConceptPhotoTextCell * cell = [OrigPubAddConceptPhotoTextCell cellWithTableView:tableView andIndexPath:indexPath andCellHeight:400];
//        self.isSelectTwoSection = YES;
        if (indexPath.row == self.proIdeasArray.count) {
            [cell setImageViewWithImage:self.tempImage];
            [cell hiddenBtnImage:NO];
        }else{
            [cell hiddenBtnImage:YES];
            [cell setImageWith:self.proIdeasArray[indexPath.row]];
        }
        // 这是 选择图片和填写设计理念
        if (indexPath.row == self.proIdeasArray.count) {
            cell.textViewEndEdBlock = ^(NSString *text, NSIndexPath *index) {
                weakSelf.tempInpuText = text;
                [weakSelf addImageAryModel];
            };
            cell.btnSelectBlock = ^(NSIndexPath *index) {
                self.isSelectTwoSection = YES;
                weakSelf.isSelectImage = YES;
                [weakSelf addOnePhoto];
                [weakSelf addImageAryModel];
            };
        }else{ // 这是 替换图片和修改原来写的设计理念
            cell.textViewEndEdBlock = ^(NSString *text, NSIndexPath *index) {
                //需要将模型中的改变替换掉
                [weakSelf resultStr:text row:index.row];
            };
            cell.btnSelectBlock = ^(NSIndexPath *index) {
                weakSelf.isSelectTwoSection = YES;
                if (weakSelf.proIdeasArray.count != index.row) {
                    // 上一个 还没有输入完成
                    weakSelf.changeImageRow = index.row;
                    weakSelf.isSelectImage = NO;
                    [weakSelf addOnePhoto];
                }else{
                    [weakSelf addImageAryModel];
                }
            };
        }
        return cell;
    }else if (section  == 3) {
        NSArray *contentArray = @[self.sexStr,self.ageStr,self.seasonStr,self.typeStr,self.sizeStr,self.accessoryStr,self.channelStr];//self.bjStr
        ModelingSelectPublishCell *cell = [ModelingSelectPublishCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.titleLabel.text = self.titleArray[indexPath.row];
        cell.contentLabel.text = contentArray[indexPath.row];
        return cell;
    }else{
        OrigPubInputTextCell * cell = [OrigPubInputTextCell cellWithTableView:tableView andIndexPath:indexPath andCellHeight:ScreenX375(60) isAdaptive:NO keyBoardType:UIKeyboardTypeNumberPad];
        NSString * title = self.numInputTitleAry[indexPath.row];
//        NSString *str = [NSString stringWithFormat:@"≤ %@",self.rewardMount];
        NSString *str = [NSString stringWithFormat:@"≤ 3"];
        NSString * placeholder = @[str][indexPath.row];
        NSString * until = @"元";
        [cell setUIWithTitle:title placeholder:placeholder until:until];
        [cell setInputText:self.rewardMoney];
        __weak __typeof(self) weakSelf = self;
        cell.inputChangeBlock = ^(NSString *string) {
            weakSelf.rewardMoney = string;
        };
        return cell;
    }
}

#pragma mark - 点击小图后显示在上面的大图的方法
-(void)seeDetailBigPic:(UIButton *)button
{
    if (self.isVedioUpload) {
        //本地视频路径
        NSURL * localVideoUrl = self.videoUrl;
        AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:localVideoUrl];
        self.currentPlayerItem = playerItem;
        self.player = [[AVPlayer alloc] initWithPlayerItem:playerItem];

        [self.player play];

    }
    NSLog(@"%ld",button.tag);
    self.selectPicsIndex = button.tag - 10000;
    UIImageView *imageV = [self.view viewWithTag:100];
    imageV.image = self.imageAry[self.selectPicsIndex];
    NSIndexPath  *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - 重新填写设计理念时，需要将模型中的改变替换掉
- (void)resultStr:(NSString *)text row:(NSInteger)row
{
    if (row >= self.proIdeasArray.count) {
        return;
    }
    AddConceptModel * model = self.proIdeasArray[row];
    model.idea = text;
}

#pragma mark - 将选择的图片和填写的设计理念存放到模型中
- (void)addImageAryModel
{
    if (self.tempImage == nil || self.tempInpuText == nil) {
        return;
    }
    AddConceptModel * model = [[AddConceptModel alloc] init];
    model.picImage = self.tempImage;
    model.idea = self.tempInpuText;
    [self.proIdeasArray addObject:model];
    self.tempInpuText = nil;
    self.tempImage = nil;
    [self.tableView reloadData];
}

#pragma mark - 删除图片的方法
- (void)deleteImg:(UIButton *)button
{
    [self.imageAry removeObjectAtIndex:button.tag - 2000];
    
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    
    [self.avLayer removeFromSuperlayer];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.textView.text = textView.text;
    self.neDesignIdea = self.textView.text;
}

@end
